package com.itheima.rpc.client.cluster.loadbalance;

import com.itheima.rpc.annotation.HrpcLoadBalance;
import com.itheima.rpc.client.cluster.LoadBalanceStrategy;
import com.itheima.rpc.provider.ServiceProvider;
import com.itheima.rpc.util.IpUtil;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@HrpcLoadBalance(strategy = "hash")
public class HashLoadBalanceStrategy implements LoadBalanceStrategy {

    @Override
    public ServiceProvider select(List<ServiceProvider> serviceProviders) {
        String ip = IpUtil.getRealIp();
        int hashCode = ip.hashCode();
        int index = Math.abs(hashCode) % serviceProviders.size();
        return serviceProviders.get(index);
    }
}
